package com.gengine.global
{
	import com.gengine.core.call.*;
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
	
	public class Global extends Object
	{
		private var _caller:Caller;
		private static var _stage:Stage;
		public static var isDebugModle:Boolean = false;
		public static var isActivate:Boolean = true;
		private static const CallerType:String = "render";
		private static var _instance:Global;
		
		public function Global()
		{
			this._caller = new Caller();
			if (_instance != null)
			{
				throw new Error("Global 单例");
			}
			
		}
		
		public function initStage(stage:Stage) : void
		{
			_stage = stage;
			_stage.addEventListener(Event.RESIZE, this.onReSizeHandler, false, 99999, false);
			_stage.addEventListener(Event.ACTIVATE, this.onActivateHandler, false, 99999);
			_stage.addEventListener(Event.DEACTIVATE, this.onDeactivateHandler, false, 99999);
			_stage.addEventListener(Event.RENDER, this.onRenderHandler);
		}
		
		private function onRenderHandler(event:Event) : void
		{
			this._caller.call(CallerType);
			this._caller.removeCallByType(CallerType);
		}
		
		private function onActivateHandler(event:Event) : void
		{
			isActivate = true;
		}
		
		private function onDeactivateHandler(event:Event) : void
		{
			isActivate = false;
		}
		
		private function onReSizeHandler(event:Event) : void
		{
			if (event.target is Stage == false)
			{
				event.stopImmediatePropagation();
			}
		}
		
		public function callLater(callback:Function) : void
		{
			this._caller.addCall(CallerType, callback);
			_stage.invalidate();
		}
		
		public static function get instance() : Global
		{
			if (_instance == null)
			{
				_instance = new Global;
			}
			return _instance;
		}
		
		public static function get stage() : Stage
		{
			return _stage;
		}
		
		public static function gc() : void
		{
			try
			{
				new LocalConnection().connect("foo");
				new LocalConnection().connect("foo");
			}
			catch (e)
			{
			}
		}
	}
}
